package api

import (
	"context"
	"time"

	"gitee.com/liumou_site/go-network-monitoring/service"
	"gitee.com/liumou_site/go-network-monitoring/types"
	"gitee.com/liumou_site/go-network-monitoring/utils"
	"github.com/gin-gonic/gin"
)

// SSEAPIHandler SSE实时推送API处理器
type SSEAPIHandler struct {
	networkService *service.NetworkService
	systemService  *service.SystemService
	processService *service.ProcessMonitorService
}

// NewSSEAPIHandler 创建SSE API处理器实例
func NewSSEAPIHandler(startTime time.Time) *SSEAPIHandler {
	return &SSEAPIHandler{
		networkService: service.NewNetworkService(),
		systemService:  service.NewSystemService(startTime),
		processService: service.GetGlobalProcessMonitor(),
	}
}

// SSEDataAPI 网络监控SSE推送API
// GET /api/sse
// 处理SSE连接，实时推送网卡数据
func (h *SSEAPIHandler) SSEDataAPI(c *gin.Context) {
	// 设置SSE响应头
	c.Writer.Header().Set("Content-Type", "text/event-stream")
	c.Writer.Header().Set("Cache-Control", "no-cache")
	c.Writer.Header().Set("Connection", "keep-alive")
	c.Writer.Header().Set("Access-Control-Allow-Origin", "*")

	// 创建通知通道
	clientGone := c.Request.Context()

	// 创建定时器，每1秒推送一次数据
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()

	c.Writer.Write([]byte("data: " + `{"type":"connected","message":"SSE连接已建立"}` + "\n\n"))
	c.Writer.Flush()

	for {
		select {
		case <-ticker.C:
			// 获取网络数据
			allStats, err := h.networkService.GetNetworkStats()
			if err != nil {
				c.SSEvent("error", gin.H{"error": err.Error()})
				c.Writer.Flush()
				continue
			}

			// 计算速度
			speedStats, _, err := h.networkService.CalculateSpeed(context.Background(), 1*time.Second)
			if err != nil {
				c.SSEvent("error", gin.H{"error": err.Error()})
				c.Writer.Flush()
				continue
			}

			// 获取系统资源数据
			systemStats := h.systemService.GetSystemStatsSimple()

			// 构建网络数据
			sseData := make(map[string]interface{})
			totalDownload := 0.0
			totalUpload := 0.0
			totalDropped := 0
			activeCount := 0

			for name, stats := range allStats {
				if speed, exists := speedStats[name]; exists {
					downloadGB := float64(stats.TotalDownload) / 1024 / 1024 / 1024
					uploadGB := float64(stats.TotalUpload) / 1024 / 1024 / 1024
					dropped := stats.TotalDropped
					receivedMbps := float64(speed.DownloadSpeed) / 1024 / 1024 * 8
					sentMbps := float64(speed.UploadSpeed) / 1024 / 1024 * 8

					sseData[name] = types.InterfaceData{
						ID:              utils.GenerateInterfaceID(name),
						Name:            name,
						ReceivedMbps:    receivedMbps,
						SentMbps:        sentMbps,
						TotalReceivedGB: downloadGB,
						TotalSentGB:     uploadGB,
						Dropped:         dropped,
						Status:          "active",
						IsVirtual:       stats.IsVirtual,
						// 格式化字符串字段
						ReceivedMbpsText:  utils.FormatSpeed(speed.DownloadSpeed),
						SentMbpsText:      utils.FormatSpeed(speed.UploadSpeed),
						TotalReceivedText: utils.FormatBytesFloat(float64(stats.TotalDownload)),
						TotalSentText:     utils.FormatBytesFloat(float64(stats.TotalUpload)),
						DroppedText:       utils.FormatCount(dropped),
						UpdateTime:        utils.FormatTimeNow(),
					}

					totalDownload += downloadGB
					totalUpload += uploadGB
					totalDropped += int(dropped)
					activeCount++
				}
			}

			// 添加汇总数据
			totalTraffic := (totalDownload + totalUpload) * 1024 * 1024 * 1024
			lossRate := 0.0
			if totalTraffic > 0 {
				lossRate = float64(totalDropped) / totalTraffic * 100
			}

			summary := types.SSESummary{
				TotalInterfaces: activeCount,
				TotalDownload:   totalDownload,
				TotalUpload:     totalUpload,
				TotalLoss:       lossRate,
			}

			// 构建完整的SSE数据
			networkData := types.SSENetworkData{
				Interfaces: sseData,
				Summary:    summary,
				System:     systemStats,
			}

			// 发送SSE事件
			c.SSEvent("data", networkData)
			c.Writer.Flush()

		case <-clientGone.Done():
			return
		}
	}
}

// ProcessSSEAPI 进程监控SSE推送API
// GET /api/processes/sse
// 通过Server-Sent Events实时推送进程网络活动
func (h *SSEAPIHandler) ProcessSSEAPI(c *gin.Context) {
	// 设置SSE头
	c.Writer.Header().Set("Content-Type", "text/event-stream")
	c.Writer.Header().Set("Cache-Control", "no-cache")
	c.Writer.Header().Set("Connection", "keep-alive")
	c.Writer.Header().Set("Access-Control-Allow-Origin", "*")

	// 创建客户端连接通道
	clientGone := c.Request.Context()

	// 发送初始数据
	stats, err := h.processService.GetAllProcessStats()
	if err != nil {
		c.SSEvent("error", gin.H{"error": err.Error()})
		return
	}

	connections, err := h.processService.GetProcessConnections()
	if err != nil {
		c.SSEvent("error", gin.H{"error": err.Error()})
		return
	}

	// 获取进程监控统计
	monitoringStats := h.processService.BuildProcessMonitoringStats(stats, connections)
	processData := types.ProcessSSEData{
		Processes: stats,
		Count:     len(stats),
		Timestamp: utils.FormatTimeNow(),
		MonitoringStats: monitoringStats,
	}

	c.SSEvent("processes", processData)
	c.Writer.Flush()

	// 定时推送更新
	ticker := time.NewTicker(2 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			stats, err := h.processService.GetAllProcessStats()
			if err != nil {
				c.SSEvent("error", gin.H{"error": err.Error()})
				return
			}

			connections, err := h.processService.GetProcessConnections()
			if err != nil {
				c.SSEvent("error", gin.H{"error": err.Error()})
				return
			}

			// 获取进程监控统计
			monitoringStats := h.processService.BuildProcessMonitoringStats(stats, connections)
			processData := types.ProcessSSEData{
				Processes: stats,
				Count:     len(stats),
				Timestamp: utils.FormatTimeNow(),
				MonitoringStats: monitoringStats,
			}

			c.SSEvent("processes", processData)
			c.Writer.Flush()

		case <-clientGone.Done():
			return
		}
	}
}
